<template>
    <el-upload
            ref="uploadRef"
            :show-file-list="false"
            action="#"
            :limit="limit"
            :http-request="uploadFile"
            :on-remove="onRemove"
    >
        <div class="d-flex flex-column">
            <el-button  style="border-color: #FC7018;background-color:#fff8f6;color: #FC7018;">
                <svg-icon icon-class="project-detail-icon-l-shangchuan" class="upload-icon m-r5"></svg-icon>
                点击上传
            </el-button>
            <span style="color: #f12527;">(仅支持docx、pdf格式文档/限制上传数量:9)</span>
        </div>
    </el-upload>
    <div class="filesContent d-flex">
        <div class="files_c_item m-b10" v-for="(v, i) in files" :key="i">
            <el-icon
                color="#999999"
                class="icon_delete"
                @click="handelFileDelete(v.data)"
            >
                <CircleCloseFilled />
            </el-icon>
            <span class="icon_name" @click="fileNameClick(v.file)">
                <el-icon> <Document  /> </el-icon>
                {{ v.data.fileName }}
            </span
            >
        </div>
    </div>
</template>

<script setup>
import {ElIcon, ElLoading, ElMessage, ElUpload} from "element-plus";
import {ref} from "vue";
import {fileControlApi} from "@/api/assets";
import {CircleCloseFilled, Document} from "@element-plus/icons-vue";
import {fileApi} from "@/api/investment";
import axios from "axios";

const emits = defineEmits(['onSuccess','onRemove','onSelectFile']);
const files = ref([]);

const props = defineProps({
    /* 上传参数 */
    /* 业务类型（1房源业务，2资产业务 11招标比选会审 12招标结果会审 13招标合同会审 14招标中标通知书 15招标合同扫描件） */
    businessType: {
        type: Number,
        default: 0
    },
    /* 关联编号id */
    associationId: {
        type: String,
        default: ''
    },
    limit:{
        type:Number,
        default:9
    }
});

/**
 * el-upload 选择文件后的事件
 * @param file
 */
const uploadFile = async (file) => {
    const addTypeArray = file.file.name.split(".");
    const addType = addTypeArray[addTypeArray.length - 1]

    const loading = ElLoading.service({
        lock: true,
        text: '上传中，请稍后',
        background: 'rgba(0, 0, 0, 0.7)'
    })
    if (addType === "docx" || addType === "pdf") {
        let config = {
            headers: {
                "Content-Type": "multipart/form-data"
            },
            onUploadProgress: (event) => {
                let progress = Math.round(event.loaded / event.total * 100) | 0;
                loading.setText(`上传中，请稍后...${progress}%`);
            },
        };

        let resFile = file.file;  //注意：直接上传file文件，不要用FormData对象的形式传
        const res = await fileApi.getMinioAddress({fileName: resFile.name});
        let result = res.data.url;
        if (res.code !== '200') {
            loading.close();
            return ElMessage.error("上传失败,请联系管理员!");
        }
        //需要用put方法上传，post会报405，aws官方规定是put方法
        const resData = await axios.put(result, resFile, config);
        if (resData.status === 200) {
            files.value.unshift({
                data: {
                    associationId: props.associationId,
                    businessType: props.businessType,
                    fileName: resFile.name,
                    fileUrlKey: res.data.fileUrl,
                },
                file: file.file
            });
            emits('onSuccess', files.value);

            loading.close();
            ElMessage.success("上传成功!");
        }
        if(resData.status !== 200){
            loading.close();
            ElMessage.error("上传失败,请联系管理员!");
        }
    } else {
        ElMessage.error('请上传正确格式的文档!');
    }
}

/**
 * 文件移除
 */
const onRemove = (uploadFile,uploadFiles) => {
    emits('onRemove');
}

/**
 * 删除
 */
const handelFileDelete = (item) => {
    let i = files.value.findIndex((v) => v.fileUrlKey !== item.fileUrlKey);
    files.value.splice(i,1);
    ElMessage.success('删除成功!');
    emits('onSuccess',files.value);
}

/**
 * 文件名称被点击
 * @param file
 */
const fileNameClick = (file) => {
    emits('onSelectFile',file);
}

const clearFiles = () => {
    files.value = [];
}

defineExpose({clearFiles});
</script>

<style lang="scss" scoped>
.filesContent {
    align-items: center;
    flex-wrap: wrap;
    max-height:80px;
    overflow-y:auto;
    .files_c_item {
        min-width: 120px;
        padding: 0 30px;
        position: relative;

        .icon_delete {
            position: absolute;
            top: -1px;
            right: 10px;
            cursor: pointer;
        }
        .icon_delete:hover {
            color: red;
        }

        .icon_name {
            color: #999;
            cursor: pointer;
        }
        .icon_name:hover {
            color: #fc7018;
        }
    }
}
</style>
